import VueRouter from "vue-router";
import Vue from "vue";
import store from "@/utils/storage";

Vue.use(VueRouter);

const routes = [
  { name: "login", path: "/", component: () => import("@/views/LoginView") },
  {
    name: "index",
    path: "/index",
    component: () => import("@/views/IndexView"),
    children: [
      {
        name: "main",
        path: "/main",
        component: () => import("@/views/MainView"),
      },
      {
        name: "area",
        path: "/area",
        component: () => import("@/views/AreaView.vue"),
      },
      { name: "log", path: "/log", component: () => import("@/views/LogView") },
      {
        name: "community",
        path: "/community",
        component: () => import("@/views/CommunityView"),
      },
      {
        name: "apartment",
        path: "/apartment",
        component: () => import("@/views/ApartmentView"),
      },
      {
        name: "ApartmentAllocation",
        path: "/ApartmentAllocation",
        component: () => import("@/views/ApartmentAllocationView"),
      },
      {
        name: "audit",
        path: "/audit",
        component: () => import("@/views/AuditView"),
      },
      {
        name: "auditDetail",
        path: "/auditDetail",
        component: () => import("@/views/AuditDetailView"),
      },
      {
        name: "member",
        path: "/member",
        component: () => import("@/views/MemberView"),
      },
      {
        name: "permissions",
        path: "/permissions",
        component: () => import("@/views/PermissionsView"),
      },
      {
        name: "contract",
        path: "/contract",
        component: () => import("@/views/ContractView"),
      },
    ],
  },
];

const router = new VueRouter({
  mode: "hash",
  routes,
});

const permissionMap = {
  "/area": "区域管理",
  "/community": "小区管理",
  "/apartment": "套房管理",
  "/audit": "租客审核",
  "/apartmentAllocation": "房源分配",
  "/contract": "合同管理",
  "/member": "人员管理",
  "/permissions": "权限管理",
};

router.beforeEach((to, from, next) => {
  const isLogin = store.state.isLogin;
  const permissions = store.state.permissions || [];

  if (!isLogin) {
    if (to.path !== "/") {
      return next("/");
    }
    return next();
  }

  const requiredPermission = permissionMap[to.path];
  if (requiredPermission && !permissions.includes(requiredPermission)) {
    return next("/main");
  }

  next();
});

export default router;
